package projects.android.sms.adapter;

import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import projects.android.sms.R;
import projects.android.sms.db.DBHandle;
import projects.android.sms.encrypter.Encrypter;
import projects.android.sms.object.SMS;
import android.content.Context;
import android.graphics.Color;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * Adapter managing the SMS list.
 * 
 * @author Thomas Jaeger
 * @author Mario Kraml
 * @author Tassilo Posegga
 * @author Robert Schenkenfelder
 * 
 */
public class SMSAdapter extends ArrayAdapter<SMS> {

	private final ArrayList<SMS> smsList;

	public SMSAdapter(Context context, int textViewResourceId, ArrayList<SMS> sms) {
		super(context, textViewResourceId, sms);
		this.smsList = sms;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;
		if (v == null) {
			LayoutInflater vi = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			v = vi.inflate(R.layout.listitem, null);
		}

		SMS sms = smsList.get(position);
		if (sms != null) {
			ImageView avatar = (ImageView) v.findViewById(R.id.avatar);
			avatar.setVisibility(0);
			TextView message = (TextView) v.findViewById(R.id.message);
			TextView date = (TextView) v.findViewById(R.id.date);

			if (message != null) {
				try {
					message.setText(Encrypter.decrypt(sms.getMessage(), DBHandle.getInstance(getContext())
							.getOwnPrivateKey()));
				} catch (Exception e) {
					message.setText("");
				}
			}

			if (sms.isIncoming()) {
				v.setBackgroundColor(Color.LTGRAY);
				message.setGravity(Gravity.RIGHT);
				date.setGravity(Gravity.RIGHT);
			} else {
				v.setBackgroundColor(Color.WHITE);
				message.setGravity(Gravity.LEFT);
				date.setGravity(Gravity.LEFT);
			}

			if (date != null) {
				Date d = sms.getDate();
				DateFormat sdf = SimpleDateFormat.getDateTimeInstance();
				date.setText(sdf.format(d));
			}
		}
		return v;
	}

	public ArrayList<SMS> getUsers() {
		return smsList;
	}
}
